{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Pull Portfolio Factor Risk and Attribution Data\n",
    "\n",
    "When you create and upload positions to a portfolio in Marquee, GS Quant makes it possible to pull factor risk analytics in just a few lines of code.\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "Before you begin this tutorial, you must have a portfolio in Marquee with positions and a factor risk report that has already been created, scheduled, and completed. If that's not the case, please navigate to our tutorial on [creating a new portfolio](../tutorials/Create%20New%20Portfolio.ipynb) and/or [updating positions and running reports](../tutorials/Update%20Historical%20Portfolio.ipynb).\n",
    "\n",
    "Your application also needs to have the **run_analytics** scope. If it doesn't, please request it on your [My Applications Page](https://developer.gs.com/go/apps/view). If you have any other questions please reach out to the [Marquee sales team](mailto:gs-marquee-sales@gs.com)."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Step 1: Authenticate and Initialize Your Session\n",
    "\n",
    "First you will import the necessary modules and add your client id and client secret."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "\n",
    "import datetime as dt\n",
    "\n",
    "from gs_quant.api.gs.risk_models import GsRiskModelApi\n",
    "from gs_quant.markets.portfolio_manager import PortfolioManager\n",
    "from gs_quant.markets.report import FactorRiskReport\n",
    "from gs_quant.session import GsSession, Environment\n",
    "\n",
    "client = 'ENTER CLIENT ID'\n",
    "secret = 'ENTER CLIENT SECRET'\n",
    "\n",
    "\n",
    "GsSession.use(Environment.PROD, client_id=client, client_secret=secret, scopes=('run_analytics',))\n",
    "\n",
    "print('GS Session initialized.')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Step 2: Get all Portfolio Reports\n",
    "\n",
    "The `PortfolioManager` class allows for easy retrieval and scheduling of portfolio reports. Simply running:"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "outputs": [],
   "source": [
    "all_reports = PortfolioManager('ENTER PORTFOLIO ID').get_reports()\n",
    "\n",
    "print(all_reports)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "will return a list of `Report` objects that represent the reports associated with the portfolio.\n",
    "\n",
    "## Step 3: Retrieve the Relevant Factor Risk Report\n",
    "\n",
    "The GS Quant `Report` class is inherited by report subclasses, like `FactorRiskReport` and `PerformanceReport`, each of which corresponds to a type of Marquee report. Each subclass then has additional functions specific to its report type. In this case, we'd like to find the `FactorRiskReport` associated with this portfolio, and leverage its functions to retrieve data. First let's retrieve the list of all risk models we can choose from."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [],
   "source": [
    "list_of_risk_models = []\n",
    "for report in all_reports:\n",
    "    if isinstance(report, FactorRiskReport):\n",
    "        list_of_risk_models.append(report.get_risk_model_id())\n",
    "\n",
    "print(f'This portfolio has scheduled factor risk reports with the following risk models:\\n {list_of_risk_models}')\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "If you would like to pull factor risk data off of a risk model not on this list, you can [create and schedule a new factor risk report](../examples/marquee/00_create_factor_risk_report.ipynb).\n",
    "\n",
    "### Quick Tip!\n",
    "If you would like to see all available risk model IDs to choose from, simply run the following"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "outputs": [],
   "source": [
    "risk_models = GsRiskModelApi.get_risk_models(limit=1000)\n",
    "for risk_model in risk_models:\n",
    "    print(f'{risk_model}\\n')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "Now let's pick one risk model ID from the list above and find its correlating `FactorRiskReport`."
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "outputs": [],
   "source": [
    "risk_model_id = 'ENTER RISK MODEL ID'\n",
    "factor_risk_reports = list(filter(lambda report: isinstance(report, FactorRiskReport) and report.get_risk_model_id() == risk_model_id, all_reports))\n",
    "if len(factor_risk_reports) == 0:\n",
    "    print(f'This portfolio does not have a factor risk report with the risk model {risk_model_id}. Please create a new factor risk report and schedule it before proceeding.')\n",
    "factor_risk_report = factor_risk_reports[0]\n",
    "\n",
    "print(f'Factor risk model found with ID: \"{factor_risk_report.id}\".')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "will return a list of `Report` objects that represent the reports associated with the portfolio.\n",
    "\n",
    "## Step 4: Pull Report Data\n",
    "\n",
    "Now that we have our factor risk report, we can leverage the functionality of the `FactorRiskReport` class to pull attribution and risk data. In this example, let's pull historical data on factor, specific, and total PnL for the year 2020:"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "outputs": [],
   "source": [
    "factor_pnl = factor_risk_report.get_factor_pnl(factor_name='Factor', start_date=dt.date(2020, 1, 1), end_date=dt.date(2021, 1, 1))\n",
    "specific_pnl = factor_risk_report.get_factor_pnl(factor_name='Specific', start_date=dt.date(2020, 1, 1), end_date=dt.date(2021, 1, 1))\n",
    "total_pnl = factor_risk_report.get_factor_pnl(factor_name='Total', start_date=dt.date(2020, 1, 1), end_date=dt.date(2021, 1, 1))\n",
    "\n",
    "print(f'Factor: \\n{factor_pnl.__str__()}')\n",
    "print(f'Specific: \\n{specific_pnl.__str__()}')\n",
    "print(f'Total: \\n{total_pnl.__str__()}')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "Now let's pull the breakdown of proportion of risk among the different factor types over time:"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "outputs": [],
   "source": [
    "market_prop_of_risk = factor_risk_report.get_factor_proportion_of_risk(factor_name='Market', start_date=dt.date(2020, 1, 1), end_date=dt.date(2021, 1, 1))\n",
    "style_prop_of_risk = factor_risk_report.get_factor_proportion_of_risk(factor_name='Style', start_date=dt.date(2020, 1, 1), end_date=dt.date(2021, 1, 1))\n",
    "industry_prop_of_risk = factor_risk_report.get_factor_proportion_of_risk(factor_name='Industry', start_date=dt.date(2020, 1, 1), end_date=dt.date(2021, 1, 1))\n",
    "country_prop_of_risk = factor_risk_report.get_factor_proportion_of_risk(factor_name='Country', start_date=dt.date(2020, 1, 1), end_date=dt.date(2021, 1, 1))\n",
    "\n",
    "print(f'Market: \\n{market_prop_of_risk.__str__()}')\n",
    "print(f'Style: \\n{style_prop_of_risk.__str__()}')\n",
    "print(f'Industry: \\n{industry_prop_of_risk.__str__()}')\n",
    "print(f'Country: \\n{country_prop_of_risk.__str__()}')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Quick Tip!\n",
    "If you would like to pull all factor risk data for a list of different factors, you can use the `get_results` function:"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "factor_and_total_results = factor_risk_report.get_results(factors=['Factor', 'Specific'], start_date=dt.date(2020, 1, 1), end_date=dt.date(2021, 1, 1))\n",
    "print(factor_and_total_results.__str__())"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "\n",
    "### You're all set, Congrats! What's next?\n",
    "\n",
    "* [Creating and scheduling a new factor risk report](../examples/marquee/00_create_factor_risk_report.ipynb)\n",
    "\n",
    "* [Updating the portfolio with new positions](../tutorials/Update%20Historical%20Portfolio.ipynb)\n",
    "\n",
    "* [Retrieving the portfolio's performance analytics](../tutorials/Pull%20Portfolio%20Performance%20Data.ipynb)\n",
    "\n",
    "\n",
    "*Other questions? Reach out to the [Portfolio Analytics team](mailto:gs-marquee-analytics-support@gs.com)!*"
   ],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}